/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mnstudent.presentationlayer;

import mnstudent.businessLayer.LoginBLL;
import mnstudent.global.SConnection;
import mnstudent.global.Standard;
import mnstudent.global.Util;
import mnstudent.security.MD5;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;

/**
 *
 * @author lee
 */
public class frmLogin extends javax.swing.JFrame {

    private LoginBLL loginBLL;

    /**
     * Creates new form frmLogin
     */
    public frmLogin() {
        initComponents();
        prepare();

        //Load Config Connection
        SConnection.Init();
        loginBLL = new LoginBLL();
    }

    /**
     * Prepare
     */
    private void prepare() {

        
         //TextField tinh/quan 
        txtUserName.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    int len = txtUserName.getText().length();
                    if (len > Standard.MAX_LEN) {
                            e.consume();
                    }
                }
        });
        
         //TextField tinh/quan 
        txtPassword.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    int len = txtPassword.getText().length();
                    if (len > Standard.MAX_LEN) {
                            e.consume();
                    }
                }
        });
        //Set lai text cac button cua dialog
        UIManager.put("OptionPane.cancelButtonText", "Hủy");
        UIManager.put("OptionPane.noButtonText", "Không");
        UIManager.put("OptionPane.okButtonText", "Có");
        UIManager.put("OptionPane.yesButtonText", "Vâng");

        Image image = new ImageIcon(this.getClass().getResource("/Data/login.png")).getImage();
        jxImgLogin.setImage(image);
        jxImgLogin.setBackground(new Color(240, 240, 240));
        this.getContentPane().setBackground(new Color(240, 240, 240));
        this.setLocationRelativeTo(getRootPane());

    }

    /**
     * Login
     */
    private void login() {
        if (!txtUserName.getText().equals("")) {
            if (!txtPassword.getText().equals("")) {
                int isConnect = Util.testConnection();
                if (isConnect == 0) {
                    if (loginBLL.checkLogin(txtUserName.getText(), MD5.Hash(txtPassword.getText()))) {
                        loginBLL.loadUser(txtUserName.getText().trim(), MD5.Hash(txtPassword.getText().trim()));
                        frmMainMenu frm = new frmMainMenu();
                        frm.show();
                        this.dispose();
                    } else {
                        //JOptionPane.showMessageDialog(this, "Tên đăng nhập hoặc mật khẩu không đúng!");
                        lblStatus.setText("Tên đăng nhập hoặc mật khẩu không đúng!");
                    }
                } else if (isConnect == 1) {
                    //JOptionPane.showMessageDialog(this, "Không khởi động được Driver. Làm ơn kiểm tra kết nối CSDL");
                    lblStatus.setText("Không khởi động được Driver. Làm ơn kiểm tra kết nối CSDL");
                } else if (isConnect == 2) {
                    //JOptionPane.showMessageDialog(this, "Không mở được kết nối. Làm ơn kiểm tra kết nối CSDL");
                    lblStatus.setText("Không mở được kết nối. Làm ơn kiểm tra kết nối CSDL");
                }

            } else {
                //JOptionPane.showMessageDialog(this, "Chưa nhập mật khẩu.");
                lblStatus.setText("Chưa nhập mật khẩu.");
            }
        } else {
            //JOptionPane.showMessageDialog(this, "Chưa nhập tên đăng nhập.");
            lblStatus.setText("Chưa nhập tên đăng nhập.");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jxLabUser = new org.jdesktop.swingx.JXLabel();
        jxLabPass = new org.jdesktop.swingx.JXLabel();
        txtUserName = new org.jdesktop.swingx.JXTextField();
        txtPassword = new javax.swing.JPasswordField();
        jxImgLogin = new org.jdesktop.swingx.JXImageView();
        btnLogin = new org.jdesktop.swingx.JXButton();
        btnCancel = new org.jdesktop.swingx.JXButton();
        btnConnection = new javax.swing.JButton();
        lblStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jxLabUser.setText("Tên đăng nhập");

        jxLabPass.setText("Mật khẩu");

        txtUserName.setText("admin");
        txtUserName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUserNameKeyPressed(evt);
            }
        });

        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jxImgLoginLayout = new javax.swing.GroupLayout(jxImgLogin);
        jxImgLogin.setLayout(jxImgLoginLayout);
        jxImgLoginLayout.setHorizontalGroup(
            jxImgLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jxImgLoginLayout.setVerticalGroup(
            jxImgLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 120, Short.MAX_VALUE)
        );

        btnLogin.setText("Đăng nhập");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });
        btnLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnLoginKeyPressed(evt);
            }
        });

        btnCancel.setText("Hủy bỏ");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnConnection.setText("Kết nối CSDL");
        btnConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectionActionPerformed(evt);
            }
        });

        lblStatus.setForeground(java.awt.Color.red);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jxImgLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jxLabUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jxLabPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(25, 25, 25))
                            .addComponent(btnConnection, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtUserName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(24, 24, 24))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblStatus)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(42, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jxImgLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblStatus)
                        .addGap(9, 9, 9))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jxLabUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jxLabPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnConnection))
                        .addGap(30, 30, 30))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        login();
    }//GEN-LAST:event_btnLoginActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectionActionPerformed
        fpnlConnection _fpnlConnection = new fpnlConnection();
        _fpnlConnection.showDialog(frmLogin.this, "Kết nối với cơ sở dữ liệu");

    }//GEN-LAST:event_btnConnectionActionPerformed

    private void txtUserNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUserNameKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) //if (!txtUserName.getText().equals(""))
        {
            login();
        }
    }//GEN-LAST:event_txtUserNameKeyPressed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) //if (!txtUserName.getText().equals(""))
        {
            login();
        }
    }//GEN-LAST:event_txtPasswordKeyPressed

    private void btnLoginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnLoginKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            login();
        }
    }//GEN-LAST:event_btnLoginKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new frmLogin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXButton btnCancel;
    private javax.swing.JButton btnConnection;
    private org.jdesktop.swingx.JXButton btnLogin;
    private org.jdesktop.swingx.JXImageView jxImgLogin;
    private org.jdesktop.swingx.JXLabel jxLabPass;
    private org.jdesktop.swingx.JXLabel jxLabUser;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JPasswordField txtPassword;
    private org.jdesktop.swingx.JXTextField txtUserName;
    // End of variables declaration//GEN-END:variables
}
